﻿using Dapper;
using Max.PH6_2009A.LowCode.Domain;
using Max.PH6_2009A.LowCode.DTO;
using Max.PH6_2009A.LowCode.IRespository;
using Max.PH6_2009A.LowCode.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH6_2009A.LowCode.Service
{
    public class RoleService : BaseService<RoleModel>, IRoleService
    {
        IUnitOfWork _unitOfWork;
        public RoleService(IRoleRespository respository, IUnitOfWork unitOfWork) : base(respository)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 添加角色的同时，分配菜单权限
        /// </summary>
        public (bool, string) InsertRoleAndMenu(RoleInsertMenuDto dto)
        {
            /*
             * //1、添加角色
             * //2、添加这个角色对应的菜单
             * 执行好几条sql，需要用到事务
             * **/

            var _db = _unitOfWork.GetDbConnection();
            _db.Open();
            using (var tran = _db.BeginTransaction()) //开启事务
            {
                try
                {
                    string sql = "";
                    Guid id = Guid.Empty;

                    if (string.IsNullOrEmpty(dto.RoleId))
                    {
                        //表示添加新的角色
                        id = Guid.NewGuid();

                        //在添加角色的同时，验证角色名不能重复
                        sql = "select  * from tb_role where name=@name";
                        var m = _db.Query(sql, new { name = dto.RoleName }, tran).FirstOrDefault();
                        if (m != null)
                        {
                            //角色名称已存在，不能继承添加
                            return (false, "角色名称存在");
                        }

                        //添加新角色
                        sql = "insert into tb_role(id,name) values(@id,@name)";
                        _db.Execute(sql, new { id = id, name = dto.RoleName }, tran);
                    }
                    else
                    {
                        //表示修改
                        id = new Guid(dto.RoleId);

                        //这里暂时没有处理修改角色名称这个功能

                        //如果是修改，需要把原来的权限菜单删除再添加
                        sql = "delete from tb_role_menu where roleid=@roleid";
                        _db.Execute(sql, new { roleid = id }, tran);
                    }

                    //添加角色对应的多个菜单
                    sql = "insert into tb_role_menu(roleid,menuid) values(@roleid,@menuid)";
                    List<RoleMenuModel> roleMenus = new List<RoleMenuModel>();
                    dto.MenuIds.ForEach(x =>
                    {
                        roleMenus.Add(new RoleMenuModel
                        {
                            MenuId = new Guid(x),
                            RoleId = id
                        });
                    });
                    _db.Execute(sql, roleMenus, tran);

                    tran.Commit();  //事务提交
                    return (true, "添加成功");
                }
                catch (Exception ex)
                {
                    tran.Rollback(); //事务回滚
                    return (false, ex.Message);
                }
            }

        }

        /// <summary>
        /// 获取角色对应的权限菜单列表
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public IEnumerable<string> GetRoleMenuById(string roleId)
        {

            string sql = "select * from tb_role_menu where roleid=@roleid";
            IEnumerable<RoleMenuModel> data = _unitOfWork.GetDbConnection().Query<RoleMenuModel>(sql, new { roleid = roleId });

            var result = data.Select(x => x.MenuId.ToString());

            return result;
        }
    }
}
